package com.ruoyi.web.controller.net;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.net.domain.ElementPortLoopback;
import com.ruoyi.net.domain.ElementPortMode;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.Device;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.IElementPortLoopbackService;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.ElementMplsLsrid;
import com.ruoyi.net.service.IElementMplsLsridService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 网元-MPLS LSR IDController
 * 
 * @author xxcg
 * @date 2024-11-19
 */
@Api(tags = "网元-MPLS LSR ID")
@RestController
@RequestMapping("/element/mpls/lsrid")
public class ElementMplsLsridController extends BaseController {
    @Autowired
    private IElementMplsLsridService elementMplsLsridService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IElementPortLoopbackService elementPortLoopbackService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 读取网元-MPLS LSR ID列表
     */
    @ApiOperation(value = "读取网元-MPLS LSR ID列表", httpMethod = "GET")
//    @PreAuthorize("@ss.hasPermi('net:lsrid:list')")
    @GetMapping("/read")
    public TableDataInfo read(ElementMplsLsrid elementMplsLsrid) {
        List<ElementMplsLsrid> elementMplsLsrids = new ArrayList<>();
        StringBuilder xml = new StringBuilder();
        xml.append("<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                "    <mpls-te>" +
                "      <router-id></router-id>" +
                "    </mpls-te>" +
                "  </mpls>");
        NetElement netElement = netElementService.getCacheObject(elementMplsLsrid.getElementId());
        Device device = deviceManager.getDevice(netElement.getIp());
        // TODO: 2024/12/9 从设备获取 接口信息
        if (device.isConnected()) {
            String rpcReply = deviceManager.getConfig(xml.toString());
            // 解析xml
            NodeList list = findNetConfXmlNodes(rpcReply, "//mpls-te");
            if (list != null && list.getLength() > 0) {
                for (int i = 0; i < list.getLength(); i++) {
                    ElementMplsLsrid entity = new ElementMplsLsrid();
                    Node node = list.item(i);
                    // 通过标签名获取节点的值
                    entity.setLsrId(getXmlLabelValue(node, "router-id"));
                    entity.setStatus("1"); // 从设备读取到的配置，设置状态为激活

                    elementMplsLsrids.add(entity);
                }
            }
        }
        startPage();
        return getDIYPageTable(elementMplsLsrids);
    }

    /**
     * 查询网元-MPLS LSR ID列表
     */
    @ApiOperation(value = "查询网元-MPLS LSR ID列表", httpMethod = "GET")
//    @PreAuthorize("@ss.hasPermi('net:lsrid:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementMplsLsrid elementMplsLsrid) {
        startPage();
        List<ElementMplsLsrid> list = elementMplsLsridService.selectElementMplsLsridList(elementMplsLsrid);
        return getDataTable(list);
    }

    /**
     * 导出网元-MPLS LSR ID列表
     */
    @ApiOperation(value = "导出网元-MPLS LSR ID列表", httpMethod = "POST")
//    @PreAuthorize("@ss.hasPermi('net:lsrid:export')")
    @Log(title = "网元-MPLS LSR ID", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementMplsLsrid elementMplsLsrid) {
        List<ElementMplsLsrid> list = elementMplsLsridService.selectElementMplsLsridList(elementMplsLsrid);
        ExcelUtil<ElementMplsLsrid> util = new ExcelUtil<ElementMplsLsrid>(ElementMplsLsrid.class);
        util.exportExcel(response, list, "网元-MPLS LSR ID数据");
    }

    /**
     * 获取网元-MPLS LSR ID详细信息
     */
    @ApiOperation(value = "获取网元-MPLS LSR ID详细信息", httpMethod = "GET")
    @PreAuthorize("@ss.hasPermi('net:lsrid:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementMplsLsridService.selectElementMplsLsridById(id));
    }

    /**
     * 新增网元-MPLS LSR ID
     */
    @ApiOperation(value = "新增网元-MPLS LSR ID", httpMethod = "POST")
//    @PreAuthorize("@ss.hasPermi('net:lsrid:add')")
    @Log(title = "网元-MPLS LSR ID", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementMplsLsrid elementMplsLsrid) {
        return toAjax(elementMplsLsridService.insertElementMplsLsrid(elementMplsLsrid));
    }

    /**
     * 修改网元-MPLS LSR ID
     */
    @ApiOperation(value = "修改网元-MPLS LSR ID", httpMethod = "PUT")
//    @PreAuthorize("@ss.hasPermi('net:lsrid:edit')")
    @Log(title = "网元-MPLS LSR ID", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementMplsLsrid elementMplsLsrid) {
        return toAjax(elementMplsLsridService.updateElementMplsLsrid(elementMplsLsrid));
    }

    /**
     * 删除网元-MPLS LSR ID
     */
    @ApiOperation(value = "删除网元-MPLS LSR ID", httpMethod = "DELETE")
//    @PreAuthorize("@ss.hasPermi('net:lsrid:remove')")
    @Log(title = "网元-MPLS LSR ID", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementMplsLsridService.deleteElementMplsLsridByIds(ids));
    }

    /**
     * 刷新
     */
    @ApiOperation(value = "刷新", httpMethod = "GET")
    @GetMapping(value = "/refresh/{ip}")
    public AjaxResult refresh(@PathVariable("ip") String ip) {
        // TODO: 2024/12/9 从设备获取 接口信息
        Device device = deviceManager.getDevice(ip);
        if (device.isConnected()) {
            StringBuilder xml = new StringBuilder();
            xml.append("<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                    "    <mpls-te>" +
                    "       <router-id></router-id>" +
                    "    </mpls-te>" +
                    "  </mpls>");
            String rpcReply = deviceManager.getConfig(xml.toString());
            // 解析xml，如果接口名称存在，批量更新条目状态为 激活
            /*List<String> list = findNetConfXmlNodes(rpcReply, "//mpls-te/router-id");
            if (!StringUtils.isEmpty(list)) {
//                elementMplsLsridService.updateStatus(list.toArray(new String[]{}), "1");
            }*/
        }
        return AjaxResult.success();
    }

    /**
     * 激活设备
     *
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/activate/{id}")
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementMplsLsrid entity = elementMplsLsridService.selectElementMplsLsridById(id);
        entity.setStatus("1");
        if (sendXml(entity)) {
            return toAjax(elementMplsLsridService.updateElementMplsLsrid(entity));
        } else {
            return AjaxResult.error("激活失败");
        }
    }

    /**
     * 去激活设备
     *
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementMplsLsrid entity = elementMplsLsridService.selectElementMplsLsridById(id);
        entity.setStatus("0");
        if (sendXml(entity)) {
            return toAjax(elementMplsLsridService.updateElementMplsLsrid(entity));
        } else {
            return AjaxResult.error("去激活失败");
        }
    }

    /**
     * 发送xml到设备
     *
     * @param entity
     */
    private boolean sendXml(ElementMplsLsrid entity) {
        boolean isSend = false;
        NetElement netElement = netElementService.getCacheObject(entity.getElementId());
        Device device = deviceManager.getDevice(netElement.getIp());
        if (device.isConnected()) {
            String operation = "create";
            // 0 未激活
            if ("0".equals(entity.getStatus())) {
                operation = "remove";
            }

            ElementPortLoopback loopback = elementPortLoopbackService.selectElementPortLoopbackById(entity.getLoopbackId());

            String xml = "<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                    "    <mpls-te>" +
                    "      <router-id nc:operation=\"" + operation + "\">" + loopback.getIp() + "</router-id>" +
                    "    </mpls-te>" +
                    "  </mpls>";
            // todo 2025-02-07 测试通过
            logger.info("MPLS LSR ID激活xml:" + xml);
            isSend = deviceManager.editConfig(xml, "merge");
        }
        return isSend;
    }
}